﻿using System;
using Autofac;
using Drill.Extensibility;

namespace Drill.DrillBits.Autofac
{
	public abstract class AutofacDrillBitSetup 
		: DrillBitSetupBase<AutofacDrillBit, ContainerBuilder>
	{
		public override void Configure(IDrillBit drillBit, object state)
		{
			base.Configure(drillBit, state);

			// Explicitly set the DrillBit's container to complete and activate the configuration.
			AutofacDrillBit autofacDrillBit = (AutofacDrillBit)drillBit;
			ContainerBuilder builder = (ContainerBuilder)state;
			IContainer container;

			try
			{
				container = builder.Build();
			}
			catch (Exception ex)
			{
				throw new AutofacDrillBitException(
					ex
				  , "An exception occurred while attempting to build the Autofac container using the "
				  + "DrillBit setup '{0}'."
				  + "See the inner exception for details."
				  , typeof(AutofacDrillBitSetup).FullName
					);
			}

			autofacDrillBit.SetContainer(container);
		}
	}
}